package top.goldenyear.porpoise.system.setting.service;

import cn.hutool.v7.core.text.StrUtil;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.solon.annotation.Db;
import top.goldenyear.porpoise.common.core.exception.ErrorCode;
import top.goldenyear.porpoise.common.core.exception.ServiceException;
import top.goldenyear.porpoise.common.core.model.PlainOption;
import top.goldenyear.porpoise.framework.common.util.object.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import top.goldenyear.porpoise.framework.web.core.annotation.Deform;
import top.goldenyear.porpoise.framework.web.core.model.PageResult;
import top.goldenyear.porpoise.framework.web.core.model.query.QPage;
import top.goldenyear.porpoise.framework.web.core.service.BaseService;
import top.goldenyear.porpoise.system.setting.dto.DictItemDto;
import top.goldenyear.porpoise.system.setting.dto.DictItemSearchReq;
import top.goldenyear.porpoise.system.setting.model.DictItem;
import top.goldenyear.porpoise.system.setting.model.proxy.DictItemProxy;

/**
 * 字典数据表 Service 服务层
 *
 * @author airhead
 * @since 2024-10-15
 */
@Component
@Slf4j
public class DictItemService extends BaseService<DictItem, DictItemProxy> implements IDictItemService {
  @Db
  private EasyEntityQuery easyEntityQuery;

  public DictItemService() {
    super(DictItem.class, DictItemProxy.class);
  }

  public Boolean createDictItem(DictItem dictItem) {
    Boolean exists = exists(dictItem);
    if (exists) {
      throw new ServiceException(ErrorCode.builder().msg("字典项已存在").build());
    }
    return save(dictItem);
  }

  public Boolean updateDictItem(DictItem dictItem) {
    Boolean exists = exists(dictItem);
    if (exists) {
      throw new ServiceException(ErrorCode.builder().msg("字典项已存在").build());
    }

    return updateById(dictItem);
  }

  public DictItem getDictItem(Integer id) {
    return getById(id);
  }

  public Boolean deleteDictItem(Integer id) {
    if (getById(id) == null) {
      throw new ServiceException(ErrorCode.builder().msg("字典项不存在").build());
    }

    return deleteById(id);
  }

  public List<DictItem> listDictItem(DictItem dictItem) {
    return list(dictItem);
  }

  @Deform(keep = {"id", "name", "value", "color_type", "css_class", "dict_code"})
  public List<DictItem> simpleListDictItem(DictItem dictItem) {
    if (dictItem == null) {
      return new ArrayList<>();
    }
    dictItem.setStatus(1);

    return list(dictItem);
  }

  public DictItem getDictItem(DictItem dictItem) {
    return get(dictItem);
  }

  public List<PlainOption> options(String dictCode) {
    if (StrUtil.isBlank(dictCode)) {
      return new ArrayList<>();
    }

    return easyEntityQuery
        .queryable(DictItem.class)
        .where(
            dictItemProxy -> {
              dictItemProxy.dictCode().eq(dictCode);
              dictItemProxy.status().eq(1);
            })
        .select(PlainOption.class)
        .toList();
  }

  public PageResult<DictItem> paginateDictItem(QPage qPage, DictItemSearchReq searchReq) {
    if (StrUtil.isBlank(searchReq.getDictCode())) {
      return PageResult.of(qPage);
    }

    return paginate(
        qPage,
        dictItemProxy -> {
          dictItemProxy.dictCode().eq(searchReq.getDictCode());
          dictItemProxy.status().eq(searchReq.getStatus());
          dictItemProxy.or(
              () -> {
                dictItemProxy.name().like(searchReq.getKeyword());
                dictItemProxy.value().like(searchReq.getKeyword());
              });
        });
  }

  @Override
  public void validateDictDataList(String dictCode, Collection<String> values) {}

  @Override
  public DictItemDto getDictItem(String dictCode, String value) {
    DictItem query = new DictItem();
    query.setDictCode(dictCode);
    query.setValue(value);
    DictItem dictItem = get(query);
    return BeanUtils.toBean(dictItem, DictItemDto.class);
  }

  @Override
  public DictItemDto parseDictItem(String dictCode, String name) {
    DictItem query = new DictItem();
    query.setDictCode(dictCode);
    query.setName(name);
    DictItem dictItem = get(query);
    return BeanUtils.toBean(dictItem, DictItemDto.class);
  }

  @Override
  public List<DictItemDto> getDictItemList(String dictCode) {
    DictItem query = new DictItem();
    query.setDictCode(dictCode);
    List<DictItem> list = list(query);
    return BeanUtils.toBean(list, DictItemDto.class);
  }

  @Override
  protected EasyEntityQuery easyEntityQuery() {
    return easyEntityQuery;
  }

  private Boolean exists(DictItem dictItem) {
    return entityQueryable()
            .where(
                dictItemProxy -> {
                  dictItemProxy.dictCode().eq(dictItem.getDictCode());
                  dictItemProxy.value().eq(dictItem.getValue());
                  dictItemProxy.id().ne(dictItem.getId());
                })
            .firstOrNull()
        != null;
  }
}
